package com.ambition.mallchat.common.user.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ambition.mallchat.common.user.dao.UserDao;
import com.ambition.mallchat.common.user.domain.entity.User;
import com.ambition.mallchat.common.user.service.UserService;
import com.ambition.mallchat.common.user.service.WxMsgService;
import com.ambition.mallchat.common.user.service.adapter.TextBuilder;
import com.ambition.mallchat.common.user.service.adapter.UserAdapter;
import com.ambition.mallchat.common.websocket.service.WebsocketService;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: mallchat-learnning
 * @ClassName WxMsgServiceImpl
 * @description:
 * @author: oldTea
 * @create: 2023-10-28 09:17
 * @Version 1.0
 **/
@Service
@Slf4j
public class WxMsgServiceImpl implements WxMsgService {

    @Autowired
    WxMpService wxMpService;
    @Autowired
    UserDao userDao;

    @Autowired
    private UserService userService;

    @Autowired
    private WebsocketService websocketService;

    @Value("${mallchat.wx.callback}")
    private String callback;

    private static final String URL =  "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";

    /**
     * openID和code的关系
     */
    private static final ConcurrentHashMap<String,Integer> WAIT_AUTHORIZE_MAP = new ConcurrentHashMap<>();
    @Override
    public WxMpXmlOutMessage scan(WxMpService weixinService, WxMpXmlMessage wxMessage) {
        String openId = wxMessage.getFromUser();
        Integer code = getEventKey(wxMessage);
        if(ObjectUtil.isNull(code)){
            return null;
        }
        User user = userDao.getUserByOpenId(openId);
        boolean register = ObjectUtil.isNotNull(user);
        boolean authorize = register && ObjectUtil.isNotNull(user.getAvatar());

        //用户已经注册授权
        if(register && authorize){
            //走登录逻辑，根据code找到channel
            websocketService.scanLoginSuccess(code,user.getId());
        }
        if(!register){
            User insert = UserAdapter.buildUserSave(openId);
            userService.saveUser(insert);
        }
        //向前端发送等待授权的状态
        websocketService.waitAuthorize(code);
        WAIT_AUTHORIZE_MAP.put(openId,code);
        String format = String.format(URL, wxMpService.getWxMpConfigStorage().getAppId(), URLEncoder.encode(callback+"/wx/portal/public/callBack"));
        return TextBuilder.build("请先<a href=\"" + format + "\">登录</a>",wxMessage,wxMpService);

    }

    @Override
    public void authorize(WxOAuth2UserInfo userInfo) {
        String openid = userInfo.getOpenid();
        User user = userDao.getUserByOpenId(openid);
        //只需要一次授权
        if(StringUtils.isNotBlank(user.getAvatar())){
            fillUserInfo(user,userInfo);
        }
        //授权成功，移除等待授权的map,根据code找到channel
        Integer code = WAIT_AUTHORIZE_MAP.remove(openid);
        websocketService.scanLoginSuccess(code,user.getId());



    }

    private void fillUserInfo(User user, WxOAuth2UserInfo userInfo) {
        UserAdapter.authorizeUser(user.getId(),userInfo);
    }

    private Integer getEventKey(WxMpXmlMessage wxMessage) {

        try {
            String eventKey = wxMessage.getEventKey();
            String code = eventKey.replace("qrscene_", "");
            return Integer.parseInt(code);
        }catch (Exception e){
            log.error("getEvent error eventKey:{}",wxMessage.getEventKey(),e);
            return null;
        }
    }
}